import 'package:demo1/model/conversation.dart';
import 'package:demo1/provider/chatmanagerprovider.dart';
import 'package:flutter/material.dart';
import 'package:provider/provider.dart';

import 'conversation_item_ui.dart';
import '../views_chat.dart';

class ChatPage extends StatefulWidget {
  const ChatPage({Key? key}) : super(key: key);

  @override
  _ChatPageState createState() => _ChatPageState();
}

class _ChatPageState extends State<ChatPage> {
  int selectIndexOfDetail = 0;

  Function(Conversation item, int index)? onPress;
  late ChatManagerProvider chatProvider;
  @override
  void initState() {
    // TODO: implement initState
    super.initState();




  }

  showDetail(){
    if(!this.mounted)
      return;

    this.setState(() {
      selectIndexOfDetail = SingletonView.showChatDetail(chatProvider);
    });

  }

  @override
  Widget build(BuildContext context) {

    print("ChatPage:build");

    chatProvider =
        Provider.of<ChatManagerProvider>(this.context, listen: true);

    onPress = (item, index) {
      chatProvider.changeChat(item);
    };
    chatProvider.removeListener(showDetail);
    chatProvider.addListener(showDetail);

    selectIndexOfDetail = SingletonView.conversationIndex;

    final _screen = MediaQuery.of(context).size;

    var items = Row(
      mainAxisAlignment: MainAxisAlignment.start,
      children: [
        Container(
            width: _screen.width * 0.25,
            child: buildConvasationList(chatProvider)),
        VerticalDivider(width: 1.0),
        Expanded(child: SingletonView.conversationList[selectIndexOfDetail]),
      ],
    );

    return items;
  }

  Widget buildConvasationList(ChatManagerProvider chatState) {
    return Scaffold(
      appBar: AppBar(
        toolbarHeight: 35,
        shadowColor: Colors.transparent,
        title: const Text(
          '消息',
          style: TextStyle(color: Colors.white, fontSize: 18),
        ),
        actions: [],
      ),
      // ignore: avoid_unnecessary_containers
      body: buildList(context, chatState),
    );
  }

  Widget buildList(BuildContext context, ChatManagerProvider chatState) {
    return Container(
        child: ListView.builder(
      itemBuilder: (BuildContext context, int index) {
        return ConversationItem(
          chatState.conversations[index],
          index,
          0,
          (index == chatState.chatIndex),
          onPress,
        );
      },
      itemCount: chatState.conversations.length,
    ));
  }
}
